# -*- coding: utf-8 -*-
"""
Created on Tue Jul 14 17:19:16 2020

@author: Administrator
"""


from fvcore.common.file_io import PathManager
#from drawbox import path_annotation
import logging
import os
logger = logging.getLogger(__name__)


TRAIN_GT_BOX_LISTS=['ava_train_v2.2.csv']
TRAIN_PREDICT_BOX_LISTS=[]
TEST_PREDICT_BOX_LISTS=["ava_val_predicted_boxes.csv"]
ANNOTATION_DIR=r'C:\Users\Administrator\Downloads\haikang\ava\annotations'
DETECTION_SCORE_THRESH = 0.9
FULL_TEST_ON_VAL = False
#path_annotation=r'C:/Users/Administrator/Downloads/haikang/ava/annotations/ava_train_v2.2.csv'
FPS = 30
AVA_VALID_FRAMES = range(902, 1799)

 
def load_box_by_name(path_annotation, valid_frames):
    
    filename=path_annotation
    all_boxes={}
    with PathManager.open(filename,'r') as f:
        for i, line in enumerate(f):
            if i ==0:
                continue
            else :
                row = line.strip().split(',')
                nt=row[0].split('"')[1].split('#t=')
                video_name, frame_sec = nt[0], int(nt[1])#row[0], int(row[1])
                    
    
                # Box with format [x1, y1, x2, y2] with a range of [0, 1] as float.
                box_key = ",".join(row[1:5])
                box = list(map(float, row[1:5]))
                #label = -1 if row[5] == "" else int(row[5])
    
                if video_name not in all_boxes:
                    all_boxes[video_name] = {}
                    for sec in valid_frames:
                        all_boxes[video_name][sec] = {}
    
                if box_key not in all_boxes[video_name][frame_sec]:
                    all_boxes[video_name][frame_sec][box_key] = [box, []]
                    
    
                all_boxes[video_name][frame_sec][box_key][1].append(row[5])
                
    for video_name in all_boxes.keys():
        for frame_sec in all_boxes[video_name].keys():
            # Save in format of a list of [box_i, box_i_labels].
            all_boxes[video_name][frame_sec] = list(
                all_boxes[video_name][frame_sec].values()
            )
    return all_boxes



def load_boxes_and_labels( mode):
    """
    Loading boxes and labels from csv files.

    Args:
        cfg (CfgNode): config.
        mode (str): 'train', 'val', or 'test' mode.
    Returns:
        all_boxes (dict): a dict which maps from `video_name` and
            `frame_sec` to a list of `box`. Each `box` is a
            [`box_coord`, `box_labels`] where `box_coord` is the
            coordinates of box and 'box_labels` are the corresponding
            labels for the box.
    """
    gt_lists = TRAIN_GT_BOX_LISTS if mode == "train" else []
    pred_lists = (
        TRAIN_PREDICT_BOX_LISTS
        if mode == "train"
        else TEST_PREDICT_BOX_LISTS
    )
    ann_filenames = [
        os.path.join(ANNOTATION_DIR, filename)
        for filename in gt_lists + pred_lists
    ]
    ann_is_gt_box = [True] * len(gt_lists) + [False] * len(pred_lists)

    detect_thresh = DETECTION_SCORE_THRESH
    # Only select frame_sec % 4 = 0 samples for validation if not
    # set FULL_TEST_ON_VAL.
    boxes_sample_rate = (
        4 if mode == "val" and not FULL_TEST_ON_VAL else 1
    )
    all_boxes, count, unique_box_count = parse_bboxes_file(
        ann_filenames=ann_filenames,
        ann_is_gt_box=ann_is_gt_box,
        detect_thresh=detect_thresh,
        boxes_sample_rate=boxes_sample_rate,
    )
    logger.info(
        "Finished loading annotations from: %s" % ", ".join(ann_filenames)
    )
    logger.info("Detection threshold: {}".format(detect_thresh))
    logger.info("Number of unique boxes: %d" % unique_box_count)
    logger.info("Number of annotations: %d" % count)

    return all_boxes    



def parse_bboxes_file(
    ann_filenames, ann_is_gt_box, detect_thresh, boxes_sample_rate=1
):
    """
    Parse AVA bounding boxes files.
    Args:
        ann_filenames (list of str(s)): a list of AVA bounding boxes annotation files.
        ann_is_gt_box (list of bools): a list of boolean to indicate whether the corresponding
            ann_file is ground-truth. `ann_is_gt_box[i]` correspond to `ann_filenames[i]`.
        detect_thresh (float): threshold for accepting predicted boxes, range [0, 1].
        boxes_sample_rate (int): sample rate for test bounding boxes. Get 1 every `boxes_sample_rate`.
    """
    all_boxes = {}
    count = 0
    unique_box_count = 0
    for filename, is_gt_box in zip(ann_filenames, ann_is_gt_box):
        with PathManager.open(filename, "r") as f:
            for line in f:
                row = line.strip().split(",")
                # When we use predicted boxes to train/eval, we need to
                # ignore the boxes whose scores are below the threshold.
                if not is_gt_box:
                    score = float(row[7])
                    if score < detect_thresh:
                        continue

                video_name, frame_sec = row[0], int(float(row[1]))
                if frame_sec % boxes_sample_rate != 0:
                    continue

                # Box with format [x1, y1, x2, y2] with a range of [0, 1] as float.
                box_key = ",".join(row[2:6])
                box = list(map(float, row[2:6]))
                label = -1 if row[6] == "" else int(row[6])

                if video_name not in all_boxes:
                    all_boxes[video_name] = {}
                    for sec in AVA_VALID_FRAMES:
                        all_boxes[video_name][sec] = {}

                if box_key not in all_boxes[video_name][frame_sec]:
                    all_boxes[video_name][frame_sec][box_key] = [box, []]
                    unique_box_count += 1

                all_boxes[video_name][frame_sec][box_key][1].append(label)
                if label != -1:
                    count += 1

    for video_name in all_boxes.keys():
        for frame_sec in all_boxes[video_name].keys():
            # Save in format of a list of [box_i, box_i_labels].
            all_boxes[video_name][frame_sec] = list(
                all_boxes[video_name][frame_sec].values()
            )

    return all_boxes, count, unique_box_count
actions_chinese_to_english_dict = {
    # 跌倒类型
    "原地软倒": "stillfall",
    "行进软倒": "walkingfall",
    "推倒": "pushoverfall",
    "绊倒": "tripfall",
    # 其他动作
    "吃药": "medicine",
    "吃饭": "eating",
    "喝水": "drinking",
    "拿手机": "takephone",
    "拿水杯": "takecup",
    "磕碰": "knock",
    "关门": "close",
    "开门": "open",
    # 人体姿态
    "站": "stand",
    "坐": "sit",
    "蹲": "squat",
    "躺": "lie",
    "半躺":'half_lie',
    #错误
    "合格": 'qualified',
    "画面确实": 'err_camera_lacking',
    "视频缺失":'err_action_lacking',
    "光线错误": 'err_light',
    '姿态错误': 'err_pose',
    "衣着错误": 'err_sleeve',
    "视角错误": 'err_view',
    "遮挡错误": 'err_shelter',
    "未知错误": 'err_unknown',
    "中间帧": 'medium',
    "结束帧": 'end',
}

actions_english_to_chinese_dict={e:i for i, e in actions_chinese_to_english_dict.items() }